/*
 * @Description: drag model对象
 * @Autor: gufuyan
 * @Date: 2021-11-15 10:05:34
 * @lastModifiedBy: gufuyan
 * @LastEditTime: 2021-11-26
 * @lastModifiedContent:
 */
import { useState, useCallback, SetStateAction } from 'react';

export type RulesType = {
  filter: {
    cond: {
      type: string;
      method: string;
      value?: any;
      field: string;
    }[];
    rel: string;
  };
  fields: React.Key[];
  tempId: string | number;
};

export type ValidatorsType = {
  formula: string;
  remind: string;
  tempId: string | number;
};
interface IFormEventObj {
  // action?: string[];
  // action_rely?: string[];
  description: string;
  enabled: boolean;
  id: string;
  name: string;
  request?: { body: any[]; format: Format; header: any[]; method: RequestType; url: string };
  // request_rely?: string[];
  trigger: string;
}
export default () => {
  // 表单前台缓存
  const [hasCache, setHasCache] = useState(false);
  const setCache = useCallback(() => setHasCache(!hasCache), [hasCache]);
  // 拖拽到视图的数据
  const [contentItem, setContentItem] = useState<any>();
  // 配置的显隐规则清单
  const [fieldShowRules, setFieldShowRule] = useState<RulesType[]>([]);
  // 提交校验规则
  const [validators, setValidators] = useState<ValidatorsType[]>([]);
  const [formEventObj, setFormEventObj] = useState<Record<string, IFormEventObj>>({});

  // 删除组件，清空显隐规则
  const removeShowRule = (id: string) => {
    const newData = [...fieldShowRules];
    // 删除对应的id
    newData.forEach((item) => {
      // 刪除显示字段对应的id
      const sfIndex = item.fields.indexOf(id);
      if (sfIndex >= 0) item.fields.splice(sfIndex, 1);

      // 删除校验规则对应的id
      const newCond: { type: string; method: string; value?: any; field: string }[] = [];
      item.filter.cond.forEach((rule) => {
        if (rule.field != id) {
          newCond.push(rule);
        }
      });
      item.filter.cond = newCond;
    });

    const newRule: SetStateAction<RulesType[]> = [];
    newData.forEach((item) => {
      // 清除显示字段为空的所有条目, 清除校验规则为空的所有条目
      if (item.fields.length != 0 && item.filter.cond.length != 0) {
        newRule.push(item);
      }
    });

    setFieldShowRule(newRule);
  };

  return {
    config: {
      hasCache,
      contentItem,
      fieldShowRules,
      validators,
      formEventObj,
    },
    fn: {
      setCache,
      setContentItem,
      setFieldShowRule,
      removeShowRule,
      setValidators,
      setFormEventObj,
    },
  };
};
